import { PagingType } from "@Tea/model";
import promisePool from ".";
import { DataAndTotal, SelectReturn } from "../types";
import { ResultSetHeader } from "mysql2";

type a = Array<{
  name: string,
  type: string,
  data: Array<number>
}>

const a:a = [
  { name:"wei" ,type:"tt", data:[1,2,3]}
]

// 操作数据库的基础类
export class ReposBase{
  //普通查询
  query<T>(sql: string): SelectReturn<T>  {
    
    return promisePool.query(sql) as unknown as SelectReturn<T> 
  }

  // 分页查询
  pagingQuery<T, K extends PagingType>(sql: string, obj: K){
    return new Promise<DataAndTotal<T>>(async (resolve, reject) => {
      try {
        const pagingSql = `${sql} limit ${(obj.currentPage - 1) * obj.pageSize}, ${obj.pageSize}`
        const [total, list] = await Promise.all([
          this.query<T>(sql),
          this.query<T>(pagingSql)
        ])

        resolve({
          data: list[0],
          total: total[0].length,
        })
      } catch (e) {
        reject(e)
      }
    })
  }

  // updateSql
  update(sql:string) {
    return promisePool.query<ResultSetHeader>(sql)
  }

  insert(sql: string) {
    return promisePool.query<ResultSetHeader>(sql)
  }

  delete(sql: string) {
    return promisePool.query<ResultSetHeader>(sql)
  }
}